<?php

class PoliticoMapper extends SON_Db_DataMapperAbstract
{
    protected $_dbTable = "DbTable_Politico";
    protected $_model = "Politico";

    protected function _insert(SON_Db_DomainObjectAbstract $obj)
    {
        try {
            $dbTable = $this->getDbTable();
            $data = array(
                'nome' => $obj->getNome(),
                'documento' => $obj->getDocumento()
            );
            return $dbTable->insert($data);
        } catch (Zend_Exception $e) {
            throw new Exception($e);
        }
    }

    protected function _update(SON_Db_DomainObjectAbstract $obj)
    {
        try {
            $dbTable = $this->getDbTable();
            $data = array(
                'nome' => $obj->getNome(),
                'documento' => $obj->getDocumento()
            );
            $data = array_map(function($value) { return (!is_null($value) && empty($value)) ? new Zend_Db_Expr('NULL') : $value; }, $data);
            $dbTable->update(array_filter($data), array('id = ?' => $obj->getId()));
            return true;
        } catch (Zend_Exception $e) {
            throw new Exception($e);
        }
    }
    
    public function fetchPairs()
    {
    	$select = $this->getDb()->select()->from('politico', array('id', 'nome'));
    	return $this->getDb()->fetchPairs($select);
    }
    
    public function findByNome($nome)
    {
    	$db = $this->getDb();
    	$query = $db->select();
    	$query->from('politico', array('id', 'nome'))
    		->where('nome LIKE ? ', "%{$nome}%");
    	
    	return $db->fetchAll($query);
    }
    
    public function findByDocumento($documento)
    {
    	$db = $this->getDb();
    	$query = $db->select();
    	$query->from('politico')
    		->where('documento = ?', $documento);
    
    	$data = $db->fetchRow($query);
    	if ($data) {
    		return $this->_populate($data);
    	}
    }
}

